package com.hmall.search.listener;

import com.alibaba.fastjson.JSON;
import com.hmall.common.Constant.SearchConstant;
import com.hmall.common.clients.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.vo.ItemVo;
import com.hmall.search.pojo.ItemDOC;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SyncListener {
    @Autowired
    RestHighLevelClient client;
    @Autowired
    ItemClient itemClient;
    
    /**
     * 添加或修改操作时，同步修改es数据
     * @param msg
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "goods.insert.queue"),
            exchange = @Exchange(name = "goods.exchange"),
            key = "goods.insert"))
    public void insertAndUpdate(String msg){
        addES(Long.parseLong(msg));
    }
    /**
     * 删除操作时，同步删除es数据
     * @param msg
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "goods.delete.queue"),
            exchange = @Exchange(name = "goods.exchange"),
            key = "goods.delete"))
    public void delete(String msg){
        delES(Long.parseLong(msg));
    }
    public void addES(Long id){
        //根据id获取hotel对象
        ItemVo itemVo = itemClient.findById(id);
        Item item = new Item();
        BeanUtils.copyProperties(itemVo,item);
        item.setId(Long.parseLong(itemVo.getId()));
        //将hotel对象转化为DOC格式的HotelDoc对象
        ItemDOC itemDOC = new ItemDOC(item);
        //将HotelDoc对象转换为json字符串
        String jsonHotelDoc = JSON.toJSONString(itemDOC);
        //创建request对象
        IndexRequest request = new IndexRequest(SearchConstant.INDEX_NAME).id(item.getId().toString());
        //设置添加文档的字段和json数据
        request.source(jsonHotelDoc, XContentType.JSON);
        //发送请求
        try {
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public void delES(Long id){
        DeleteRequest deleteRequest = new DeleteRequest(SearchConstant.INDEX_NAME, id.toString());
        try {
            client.delete(deleteRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
